<!-- localstorage设置有效期 -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>localstorage设置有效期</title>
</head>
<body>
</body>
<script>
    const storage = {
        prefix:'csc',
        timeSign:'|csc|',
        setItem (key, value, time) {
            // 做一个key的保护
            key =  `${this.prefix}${key}`
            // 没有传入时间，默认过期时间一个月
            time = time ? new Date(time).getTime() : Date.now() + 24*60*60*1000*31
            window.localStorage.setItem(key, `${time}${this.timeSign}${JSON.stringify(value)}`)
        },
        getItem(key) {
            key = `${this.prefix}${key}`
            let value = window.localStorage.getItem(key)
            if(value) {
                let index = value.indexOf(this.timeSign)
                let time = +value.slice(0, index)
                if(time > Date.now()){
                    value = JSON.parse(value.slice(index+this.timeSign.length))
                }
                else {
                    value = null
                    window.localStorage.removeItem(key)
                }
            }
            return value
        }
    }
</script>
</html>